﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using AMS.Common;
using System.IO;

namespace AMS.UI.Forms
{
    class HtmlExporter
    {
        /// <summary>
        /// 文件的编码
        /// </summary>
        public Encoding FileEncoding { get; set; }

        HtmlBuilder html = new HtmlBuilder();

        /// <summary>
        /// 导出到HTML
        /// </summary>
        /// <param name="data"></param>
        /// <param name="savePath"></param>
        public void DataTableToHtml(DataTable data, string savePath)
        {
            html.AppendLine("<html><head>");
            html.AppendLine("<style>");
            html.AppendLine("table td {border: solid 1px #000; vnd.ms-Excel.numberformat:@; }");
            html.AppendLine("</style>");
            html.AppendLine("</head><body>");
            html.AppendLine("<table>");
            html.AppendLine("<tr style='text-align:center; font-weight: bold;'>");
            AddHead(data);
            html.AppendLine("</tr>");

            foreach (DataRow row in data.Rows)
            {
                AddDataRow(row);
            }

            html.AppendLine("</table>");
            html.AppendLine("</body></html>");

            using (StreamWriter writer = new StreamWriter(savePath, false, FileEncoding == null ? Encoding.Default : FileEncoding))
            {
                writer.WriteLine(html.ToString());
            }

        }

        private void AddDataRow(DataRow row)
        {
            html.AppendLine("<tr>");
            for (int i = 0; i < row.Table.Columns.Count; i++)
            {
                if (row[i] == null || row[i] == DBNull.Value)
                {
                    //html.AddTag("td", "style", "vnd.ms-Excel.numberformat:@", "");
                    html.AddTag("td", "", true);
                }
                else
                {
                    //html.AddTag("td", "style", "vnd.ms-Excel.numberformat:@", (string)row[i]);
                    html.AddTag("td", (string)row[i], true);
                }
            }

            html.AppendLine("</tr>");
        }

        private void AddHead(DataTable data)
        {
            foreach (DataColumn column in data.Columns)
            {
                html.AddTag("td", column.Caption, true);
            }
        }
    }
}
